package tjs.study.notes.jvm.utils.jarClash;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by Nicky.Tang on 2021/10/19 12:25 下午
 *
 * @since 02.12.10
 */
public class JarClashStarter {
    public static JarClashClassLoader jarClashClassLoader = null;

    public static void addOneClashJar(String classNamePre, String... dependenciesJar) {
        JarClashClassLoader.clashJarConfig.put(classNamePre, Arrays.asList(dependenciesJar));
    }

    public static void trustStart(Class<?> mainClass, String[] args) throws InterruptedException {
        if (jarClashClassLoader != null) {
            return;
        }
        jarClashClassLoader = new JarClashClassLoader();
        Thread thread = new Thread(() -> {
            restartMain(mainClass, args, jarClashClassLoader);
        });
        thread.setName("JarClashStarter");
        thread.setDaemon(false);
        thread.setContextClassLoader(jarClashClassLoader);
        thread.start();
        thread.join();
        throw new RuntimeException("旧的线程，结束掉。。。");
    }

    private static void restartMain(Class<?> mainClass, String[] args, JarClashClassLoader loader) {
        try {
//            Class<?> mainClassRestart = Class.forName(mainClass.getName(), false, loader);
            Class<?> mainClassRestart = loader.loadBySelfFirst(mainClass.getName(), false);
            Method mainMethod = mainClassRestart.getDeclaredMethod("main", String[].class);
            mainMethod.invoke(null, new Object[]{args});//直接传args，标识多个参数；而实际上只有一个，所以要转成Object
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
}
